package io.gitee.tuo_tuo.jfinaldevassistance.generator;

import com.jfinal.json.Json;
import io.gitee.tuo_tuo.jfinaldevassistance.common.config.DevConfig;
import io.gitee.tuo_tuo.jfinaldevassistance.common.model.Dictionary;
import io.gitee.tuo_tuo.jfinaldevassistance.test.JFinalTestSupport;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.junit.Test;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class _DictionaryGenerator extends JFinalTestSupport<DevConfig> {

	@Test
	public void javaTest(){
		List<Dictionary> dictionaries = Dictionary.dao.find("select * from t_dictionary");
		String content = "";
		String pre = "public static final int ";
		for(int i = 0; i < dictionaries.size(); i++){
			String parentPre = "";
			String parentEnd = "";
			Dictionary dictionary = dictionaries.get(i);
			Integer parentId =  dictionary.getParentId();
			while (parentId != null){
				Dictionary parent = Dictionary.dao.findById(parentId);
				parentPre = parent.getDicCode() + "_";
				parentEnd = parent.getDicName() + "_";
				parentId = parent.getParentId();
			}
			content += pre + StringUtils.upperCase(parentPre + dictionary.getDicCode() + "_" +
					+ dictionary.getDicValue()) + " = " + dictionary.getDicValue() +
					"; //" + parentEnd + dictionary.getDicName() + "_" + dictionary.getDicItemName() + "\n";
		}
		System.out.println(content);
	}

	@Test
	public void jsTest() throws IOException {
		File templateFile = new File("src/test/java/io/gitee/tuo_tuo/jfinaldevassistance/generatordictionary.js.tmp");
		File targetFile = new File("src/main/webapp/js/common/dictionary.js");
		String dicString = FileUtils.readFileToString(templateFile);
		List<Dictionary> dictionaries = Dictionary.dao.find("select * from t_dictionary order by dic_id");
		Map<String , List<Dictionary>> map = new LinkedHashMap();
		for(int i = 0; i < dictionaries.size(); i++){
			Dictionary dictionary = dictionaries.get(i);
			List<Dictionary> dictionaryList = map.get(dictionary.getDicCode());
			if(dictionaryList == null){
				dictionaryList = new ArrayList<>();
				dictionaryList.add(dictionary);
				map.put(dictionary.getDicCode(), dictionaryList);
			}else {
				dictionaryList.add(dictionary);
			}
		}

		String content = Json.getJson().toJson(map);

		FileUtils.writeStringToFile(targetFile, dicString.replace("${dic_content}", content));
	}
}